<template>
    <div class="divChannel">
        <div class="divMainVideo">
            <video autoplay id="mainVideo"></video>
        </div>
        <div class="channelInfo">
            <div class="divItem">{{settings.channelCode}}</div>
            <div class="divItem">{{userInfo.userCode}}</div>
            <div class="divItem">{{userInfo.roleCode}}</div>
        </div>
        <div class="divLocal">
            <ul class="lstVideos">
                <li
                    v-for="(item,index) in objs.pushers"
                    :key="index"
                >
                    <video autoplay :id="'lv-'+item.info.code"></video>
                    <div class="divTitle">{{settings.seats[item.info.defaultSeatCode].text}}</div>
                    <div class="divAcs">
                        <div class="divItem" @click="shareScreen" :data-peercode="item.info.code">
                            <i class="fa fa-tv"></i>
                        </div>
                        <div class="divItem"  >
                            <el-dropdown @command="setCamera">
                                <span class="el-dropdown-link">
                                    <i class="fa fa-camera"></i>
                                </span>
                                <el-dropdown-menu :slot="item.code">
                                    <el-dropdown-item 
                                        v-for = "(dev,devIndex) in objs.devices"
                                        :key="devIndex"
                                        :command="dev.deviceId+'$'+item.info.code"
                                    >
                                        {{dev.label}}
                                    </el-dropdown-item> 
                                </el-dropdown-menu>
                            </el-dropdown>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
        <div class="divRemote">
            <ul class="lstVideos">
                <li
                    v-for="(item,index) in objs.pullers"
                    :key="index"
                    :data-videoid="'rv-'+item.info.code"
                    @click="setMainVideo"
                >
                    <video autoplay :id="'rv-'+item.info.code"></video>
                    <div class="divTitle">{{settings.seats[item.info.defaultSeatCode].text}}</div>
                </li>
            </ul>
        </div> 
    </div>
</template>

<script>
    var kms = require("./kmsClient.js");
    export default {
        mounted(){
            var me= this;
            try { 
                me.$nextTick().then(_=>{                    
                    return me.clearSvr(false);
                }).then(_=>{                    
                    return me.init();
                }).then(_=>{
                    return me.open();
                }).then(_=>{
                    console.log('open');
                });
            } catch (er) {
                console.log(er); 
            }
        },
        data(){
            return{
                userInfo:{
                    userCode:"guest",
                    roleCode:"roleAudience"
                },
                settings:{
                    channelCode:"channelHhu202202",
                    seats:{
                        commander:{code:"commander",text:"指挥员"} ,
                        judge01:{code:"judge01",text:"裁判-01"} ,
                        judge02:{code:"judge02",text:"裁判-02"} ,
                        judge03:{code:"judge03",text:"裁判-03"} ,
                        contacts:{code:"contacts",text:"联络员"} ,
                        local01:{code:"local01",text:"现场-01"} ,
                        local02:{code:"local02",text:"现场-02"} ,
                        local03:{code:"local03",text:"现场-03"} ,
                        audience:{code:"audience",text:"观众"} ,
                    },
                    roles:{
                        roleCommander:{
                            code:'roleCommander' , 
                            text:"指挥员" , 
                            pusherSeats:["commander"],
                            pullerSeats:["judge01","judge02","judge03","local01","local02","local03","contacts"],
                        },
                        roleJudge01:{
                            code:'roleJudge01' , 
                            text:"裁判-01" , 
                            pusherSeats:["judge01"],
                            pullerSeats:["commander","local01","local02","local03" ],
                        },
                        roleJudge02:{
                            code:'roleJudge02' , 
                            text:"裁判-02" , 
                            pusherSeats:["judge02"],
                            pullerSeats:["commander","local01","local02","local03" ],
                        },
                        roleJudge03:{
                            code:'roleJudge03' , 
                            text:"裁判-03" , 
                            pusherSeats:["judge03"],
                            pullerSeats:["commander","local01","local02","local03" ],
                        },
                        roleContacts:{
                            code:'roleContacts' , 
                            text:"联络员" , 
                            pusherSeats:["contacts"],
                            pullerSeats:["commander","local01","local02","local03" ],
                        },
                        roleLocal:{
                            code:'roleLocal' , 
                            text:"现场" , 
                            pusherSeats:["local01" ,"local02" ,"local03" ],
                            pullerSeats:["commander","judge01","judge02","judge03" ],
                        },
                        roleAudience:{
                            code:'roleAudience' , 
                            text:"观众" , 
                            pusherSeats:[],
                            pullerSeats:["local01" ,"local02" ,"local03"  ],
                        },
                    }
                },
                objs:{
                    model: new kms.THhKmsModel(),
                    devices:[],
                    pushers:[],
                    pullers:[]
                }
            }
        },
        methods:{
            init(){
                var me = this;
                return new Promise((success, faild) => {
                    try { 
                        var userCode = me.$route.query.uid;
                        userCode = userCode && userCode!=null && userCode.length>0 ? userCode :"guest";
                        var roleCode = me.$route.query.role;
                        var roleFlag =  roleCode && roleCode!=null && roleCode.length>0 && 
                            me.settings.roles[roleCode] && me.settings.roles[roleCode]!=null;
                        roleCode = roleFlag? roleCode :"roleAudience";
                        me.userInfo.userCode = userCode ;
                        me.userInfo.roleCode = roleCode ;
                        var role = me.settings.roles[me.userInfo.roleCode];

                        var modelSettings= {
                            channelCode: me.settings.channelCode,
                            seats: [ 
                                /* seatCode , title */
                            ],
                            pushers: [ 
                                /* code , title , defaultSeatCode , deviceId , video */
                            ],
                            pullers: [ 
                                /* code , title , defaultSeatCode , deviceId , video */
                            ],
                        };

                        modelSettings.seats=[];
                        Object.values(me.settings.seats).forEach( s=>{
                            modelSettings.seats.push({
                                seatCode: s.code , title: s.text
                            });
                        });

                        modelSettings.pushers=[];
                        var pushers =[];
                        role.pusherSeats.forEach( p=>{
                            var code = ['pusher' , roleCode , userCode ,p].join('_');
                            var videoId = 'lv-'+ p.code;
                            var video = document.getElementById(videoId);                            
                            var item = {
                                code: code, title: role.text+"-"+userCode, defaultSeatCode: p, deviceId: "", video:video
                            };
                            modelSettings.pushers.push(item);
                            pushers.push({
                                info: item ,
                                kmsPeer: null
                            })
                        });
                        me.objs.pushers = pushers;

                        modelSettings.pullers=[];
                        var pullers =[];
                        role.pullerSeats.forEach( p=>{
                            var code = ['puller' , roleCode , userCode ,p].join('_');
                            var videoId = 'rv-'+ p.code;
                            var video = document.getElementById(videoId);                           
                            var item = {
                                code: code, title: role.text+"-"+userCode, defaultSeatCode: p, deviceId: "", video:video
                            };                
                            modelSettings.pullers.push(item);
                            pullers.push({
                                info: item ,
                                kmsPeer: null
                            })
                        });
                        me.objs.pullers = pullers;

                        me.objs.model.settings = modelSettings;

                        me.objs.model.connection.getDevices().then(devs=>{   
                            me.objs.devices = devs.videoinput;
                            success();
                        })
                    } catch (er) {
                        console.log(er);
                        success();
                    }
                });
            },
            clearSvr( flag ){
                var me = this;
                return new Promise((success, faild) => {
                    try { 
                        if( flag){
                            me.objs.model.connection.getChannels().then(chs=>{
                                var f=()=>{
                                    if( chs.length>0){
                                        var ch = chs.shift();
                                        me.objs.model.connection.closeChannel(ch.channelCode).then(_=>{
                                            f();
                                        })
                                    }
                                    else{
                                        success();
                                    }
                                }
                                f();
                            });
                        }
                        else{
                            success();
                        }
                    } catch (er) {
                        console.log(er);
                        success();
                    }
                });
            },
            open(){
                var me = this;
                return new Promise((success, faild) => {
                    try {  
                        me.objs.model.open(_=>{
                            success();
                        });

                    } catch (er) {
                        console.log(er);
                        success();
                    }
                });
            },
            setCamera(e){
                var me = this;
                return new Promise((success, faild) => {
                    try {  
                        var arr = e.split('$');
                        var deviceId = arr[0];
                        var peerCode = arr[1];
                        var kmsPeer = me.objs.model.pushers[peerCode].kmsPeer;
                        kmsPeer.setCamera(deviceId); 


                    } catch (er) {
                        console.log(er);
                        success();
                    }
                });
            },
            shareScreen(e){
                var me = this;
                return new Promise((success, faild) => {
                    try {  
                        var peerCode = e.currentTarget.dataset.peercode;
                        var kmsPeer = me.objs.model.pushers[peerCode].kmsPeer;
                        kmsPeer.shareScreen();
                        
                        console.log( peerCode , me.objs.pushers);


                    } catch (er) {
                        console.log(er);
                        success();
                    }
                });
            },
            setMainVideo(e){
                var me = this;
                return new Promise((success, faild) => {
                    try {
                        var stream = document.getElementById( e.currentTarget.dataset.videoid).srcObject;
                        var v = document.getElementById('mainVideo');
                        v.srcObject = stream;

                    } catch (er) {
                        console.log(er);
                        success();
                    }
                });
            }
        }
    }
</script>

<style lang="less" scoped>
    .divChannel{
        height: 100%;
        position: relative;
        color: #fff;

        .divMainVideo{
            position: relative;
            height: 100%;
        }

        .channelInfo{
            position: absolute;
            left: 50%;
            top: 20px;
            transform: translate(-50%);
            display: flex;
            align-items: center;
            background-color: rgb(14, 47, 138);
            border-radius: 15px;
            .divItem{
                height: 30px;
                line-height: 30px;
                padding: 0px 10px;

            }
        }

        .divLocal{
            position: absolute;
            left: 20px;
            bottom: 20px;            
        }
        .divRemote{
            position: absolute;
            right: 20px;
            bottom: 20px;
        }

        ul.lstVideos{
            list-style: none;
            padding: 0;
            margin: 0;
            border: 1px solid #444;
            display: flex;
            li{
                position: relative;
                height: 90px;
                width: 160px;
                border: 1px solid #444;

                .divTitle{
                    position: absolute;
                    left:5px; 
                    top:4px;
                    font-size: 0.8em;
                }

                .divAcs{
                    position: absolute;
                    right:5px; 
                    top:4px;
                    font-size: 0.8em;
                    i:hover{
                        cursor: pointer;
                        color: aqua;
                    }
                }
            }
            
        }


    }

    video{
        position: absolute;
        left: 0;
        height: 0;
        top: 0;
        left: 0;
        background-color: #222;
        object-fit: cover;
        height: 100%;
        width: 100%;
    }
</style>